import { Like, FindOptionsWhere } from 'typeorm';
import { ReqProvider } from "@/core/providers/req.provider";
import { DbService } from "@/db/db.service";
import { VideoEntity } from "@/db/entitys/video.entity";
import IResponse from "@/services/response.service";
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { concatMap, defer, delay, from, map, of } from "rxjs";
import { IWonewSer } from '@/typing';

@Injectable()
export class VideoCutTemplateService {
  constructor(
    private readonly dbService: DbService,
    private readonly reqProvider: ReqProvider,
    private readonly configService: ConfigService,
  ) {}

  getList(opt?: IWonewSer.QueryFilterParams) {
    const user = this.reqProvider.user
    const page = opt?.page || 1
    const pageSize = opt.pageSize || this.configService.get("PAGE_SIZE", 30)
    const skip = (page - 1) * pageSize
    const whereOptions: FindOptionsWhere<VideoEntity> = {
      uid: user.id
    }
    if (opt.keyword) {
      whereOptions["name"] = Like(`%${opt.keyword}%`)
    }
    return defer(() => 
      this.dbService.videoCutTemplateRepository.find({where: whereOptions, skip, take: pageSize})
    ).pipe(
      concatMap(list => 
        this.dbService.videoCutTemplateRepository.count().then(total => {
          return {
            list, total, pageSize, page,
          }
        })
      ),
      map(res => IResponse.success(res))
    )
  }

  createOrUpdate(id: number, data: Partial<VideoEntity>) {
    const user = this.reqProvider.user
    return from(
      id ? this.dbService.videoCutTemplateRepository.findOneByOrFail({uid: user.id, id}) : Promise.resolve(new VideoEntity())
    ).pipe(
      concatMap(videoEntity => {
        Object.keys(data).forEach(key => {
          videoEntity[key] = data[key]
        })
        videoEntity.uid = user.id
        return this.dbService.videoCutTemplateRepository.save(videoEntity, {reload: true})
      }),
      map(videoEntity => IResponse.success(videoEntity))
    )
  }

  delete(id: number) {
    const user = this.reqProvider.user
    return defer(() =>
      this.dbService.videoCutTemplateRepository.findOneByOrFail({id, uid: user.id})
    ).pipe(
      concatMap(ent => {
        return this.dbService.videoCutTemplateRepository.remove(ent)
      }),
      delay(1000),
      map(() => IResponse.success(null))
    )
  }
}